import logging
import time


def get_logger():
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    if not logger.hasHandlers():
        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)

        # 文件处理器
        log_filename = time.strftime("%Y-%m-%d_%H-%M-%S.log", time.localtime())
        log_file_path = f"D:/shixun/PythonProject6/reports/logs/{log_filename}"

        # 确保目录存在
        import os
        os.makedirs(os.path.dirname(log_file_path), exist_ok=True)

        try:
            file_handler = logging.FileHandler(log_file_path)
            file_handler.setLevel(logging.DEBUG)
        except Exception as e:
            print(f"创建日志文件失败: {e}")
            # 如果文件处理器创建失败，仅用控制台输出
            file_handler = None

        # 配置格式
        formatter = logging.Formatter(
            "%(asctime)s - %(levelname)s - %(name)s - %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S"
        )
        console_handler.setFormatter(formatter)
        if file_handler:
            file_handler.setFormatter(formatter)
            logger.addHandler(file_handler)

        # 添加控制台处理器
        logger.addHandler(console_handler)

    return logger